package com.sooth.micro.camunda.converter.processing.container;

import com.sooth.micro.camunda.converter.bean.BaseDefinition;
import com.sooth.micro.camunda.converter.bean.subprocess.CallActivityDefinition;
import com.sooth.micro.camunda.converter.processing.BpmnElementProcessor;
import org.camunda.bpm.model.bpmn.builder.AbstractFlowNodeBuilder;
import org.camunda.bpm.model.bpmn.builder.CallActivityBuilder;

import java.lang.reflect.InvocationTargetException;
import java.util.Objects;

public class CallActivityProcessor
        implements BpmnElementProcessor<CallActivityDefinition, AbstractFlowNodeBuilder> {

    @Override
    public String onComplete(AbstractFlowNodeBuilder flowNodeBuilder, CallActivityDefinition flowNode)
            throws InvocationTargetException, IllegalAccessException {
        CallActivityBuilder callActivityBuilder = flowNodeBuilder.callActivity();

        // create execution listener
        createExecutionListener(callActivityBuilder, flowNode);

        callActivityBuilder.getElement().setName(flowNode.getNodeName());
        callActivityBuilder.calledElement(flowNode.getCalledElement());
        String id = callActivityBuilder.getElement().getId();
        BaseDefinition childNode = flowNode.getNextNode();
        if (Objects.nonNull(childNode)) {
            return onCreate(moveToNode(callActivityBuilder, id), childNode);
        }
        return id;
    }
}
